package love.luffa.pay.server;

import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.RSAConfig;
import com.wechat.pay.java.core.RSAPublicKeyConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RSAPublicKeyNotificationConfig;
import com.wechat.pay.java.service.payments.h5.H5Service;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import jakarta.annotation.PostConstruct;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * @ClassName WXPayConfig
 * @Description TODO
 * @Author kite
 * @Date 2025/2/22 15:33
 * @Version 1.0
 **/
@Getter
@Configuration
public class WeChatPayConfig {
    /**
     * 商户号
     */
    @Value("${wechat.pay.merchantId}")
    public String merchantId;
    /**
     * 商户API私钥路径
     */
    @Value("${wechat.pay.privateKeyPath}")
    public String privateKeyPath;

    @Value("${wechat.pay.publicKeyPath}")
    public String publicKeyPath;

    /**
     * 商户证书序列号
     */
    @Value("${wechat.pay.merchantSerialNumber}")
    public String merchantSerialNumber;
    /**
     * 商户APIV3密钥
     */
    @Value("${wechat.pay.apiV3Key}")
    public String apiV3Key;
    /**
     * AppId
     */
    @Value("${wechat.pay.appId}")
    public String appId;

    private Config config;

    @PostConstruct
    public void initConfig() {
        // 使用自动更新平台证书的RSA配置
        // 一个商户号只能初始化一个配置，否则会因为重复的下载任务报错
        config = new RSAAutoCertificateConfig.Builder()
                        .merchantId(merchantId)
                        .privateKeyFromPath(privateKeyPath)
                        .merchantSerialNumber(merchantSerialNumber)
                        .apiV3Key(apiV3Key)
                        .build();
    }

    /**
     * native扫码支付
     * @return
     */
    @Primary
    @Bean()
    public NativePayService nativePayService() {
        return new NativePayService.Builder()
                .config(config)
                .build();
    }

    /**
     * 支付通知解析
     * @return
     */
    @Primary
    @Bean
    public NotificationParser notificationParser() {
        return new NotificationParser((NotificationConfig) config);
    }
}

